// uniCloud-aliyun/cloudfunctions/sites/index.obj.js (无排序版本)
const db = uniCloud.database();
const dbCmd = db.command;

module.exports = {
  _before: function () {},

  add: async function(site) {
    if (!site || !site.name) {
      return {
        errCode: 'INVALID_PARAM',
        errMsg: '站点名称不能为空'
      }
    }
    return await db.collection('sites').add(site);
  },

  delete: async function(id) {
    if (!id) {
      return {
        errCode: 'INVALID_PARAM',
        errMsg: '站点ID不能为空'
      }
    }
    return await db.collection('sites').doc(id).remove();
  },

  update: async function(params) {
    const { id, data } = params;
    if (!id || !data) {
      return {
        errCode: 'INVALID_PARAM',
        errMsg: '参数不正确'
      }
    }
    return await db.collection('sites').doc(id).update(data);
  },

  get: async function(id) {
     if (!id) {
      return {
        errCode: 'INVALID_PARAM',
        errMsg: '站点ID不能为空'
      }
    }
    return await db.collection('sites').doc(id).get();
  },

  getList: async function(params = {}) {
    // 移除了 orderBy 的默认值
    const { filter = {}, page = 1, pageSize = 20 } = params;
    let query = db.collection('sites');

    if (filter.name) {
      query = query.where({
        name: new RegExp(filter.name, 'i')
      });
    }

    const res = await query
                          // .orderBy(orderBy) // 移除了排序
                          .skip((page - 1) * pageSize)
                          .limit(pageSize)
                          .get({ getCount: true });

    return res;
  }
}